package com.qire.manhua.controller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qire.common.basic.DateUtil;
import com.qire.common.collect.ArrayUtil;
import com.qire.common.collect.MapUtil;
import com.qire.common.model.entity.City;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.EventController;
import com.qire.common.support.base.ProxyViewModel;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.FileManager;
import com.qire.manhua.activity.UserProfileEditActivity;
import com.qire.manhua.dal.service.UserProfileEditService;
import com.qire.manhua.databinding.ActivityUserProfileEditBinding;
import com.qire.manhua.dialog.popup.PickerMenu;
import com.qire.manhua.model.viewModel.IUserProfileEditViewModel;
import com.qire.manhua.view.picker.PickerViewAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

public class UserProfileEditController extends EventController<UserProfileEditActivity> {

    private UserProfileEditService editService = new UserProfileEditService();

    private ProxyViewModel<IUserProfileEditViewModel> viewModel;

    private final ProvincePickerAdapter provinceAdapter;
    private final CityPickerAdapter cityAdapter;

    public UserProfileEditController(@NonNull UserProfileEditActivity lifecycleOwner) {
        super(lifecycleOwner);

        String cityJson = FileManager.readAssetsFileContent("city.json", "");
        Map<String, City[]> cityMap = new Gson().fromJson(cityJson, new TypeToken<Map<String, City[]>>() {}.getType());
        ArrayList<String> province = new ArrayList<>(cityMap.keySet());
        provinceAdapter = new ProvincePickerAdapter(province);
        cityAdapter = new CityPickerAdapter(cityMap);
        cityAdapter.setProvince(province.get(0));
    }

    @Override
    protected void bindView() {
        ActivityUserProfileEditBinding viewDataBinder = owner.viewDataBinder();
        viewDataBinder.setUserProfileEditController(this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        this.viewModel = null;
        this.editService = null;
    }

    public void onAddition(ProxyViewModel<IUserProfileEditViewModel> viewModel) {
        this.viewModel = viewModel;
        editService.onAddition(viewModel);
    }

    /*************************************************************************************************************************/

    /** 退出按钮事件响应 */
    public void backBtnOnClick(View view) {
        owner.onBackPressed();
    }

    public void editUserPortrait(Bitmap bitmap){
        editService.uploadUserPortrait(bitmap);
    }

    public void editHeadBtnOnClick(View view) {
        new AlertDialog.Builder(view.getContext())
                .setNegativeButton("拍照", (dialog, which) -> owner.chooseFromCamera())
                .setPositiveButton("相册", (dialog, which) -> owner.chooseFromGallery())
                .setMessage("选择头像来源").show();
    }

    public void editNicknameBtnOnClick(View view) {
        EditText editText = new EditText(view.getContext());
        editText.setText(UserEntity.self.getName());
        editText.setSelection(editText.getText().length());

        // 定位光标到编辑框最后
        int width  = FrameLayout.LayoutParams.MATCH_PARENT;
        int height = FrameLayout.LayoutParams.MATCH_PARENT;
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
        layoutParams.leftMargin  = EquipmentInfoUtil.dip2px(15);
        layoutParams.rightMargin = EquipmentInfoUtil.dip2px(15);

        FrameLayout frameLayout = new FrameLayout(view.getContext());
        frameLayout.addView(editText, layoutParams);

        new AlertDialog.Builder(view.getContext())
                .setTitle("填写昵称")
                .setView(frameLayout)
                .setPositiveButton("确定", (dialog, which) -> editService.submitUserName(editText.getText().toString()))
                .setNeutralButton("取消", (dialog, which) -> {})
                .show();
    }

    public void editGenderBtnOnClick(View view) {
        new AlertDialog.Builder(view.getContext())
                .setNegativeButton("男", (dialog, which) -> editService.submitSex(true))
                .setPositiveButton("女", (dialog, which) -> editService.submitSex(false))
                .setMessage("选择你的真实性别吧").show();
    }

    public void editBirthdayBtnOnClick(View view) {

        DatePickerDialog.OnDateSetListener onDateSetListener = (DatePicker datePicker, int year, int month, int dayOfMonth)->{
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month, dayOfMonth);
            String birthday = DateUtil.yMd.format(calendar.getTime());
            editService.submitBirthday(birthday);
        };

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(view.getContext(), onDateSetListener, year, month, day);
        datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
        datePickerDialog.show();
    }

    public void editDistrictBtnOnClick(View view) {
        new PickerMenu(owner).reset()
                .setPickerViewBefore(provinceAdapter)
                .setPickerViewAfter(cityAdapter)
                .<List<String>, ProvincePickerAdapter>setBeforeOnSelectedListener((pickerView, adapter, position) -> {
                    String province = adapter.getItem(position);
                    cityAdapter.setProvince(province);
                })
                .<Map<String, City[]>, CityPickerAdapter>setAfterOnSelectedListener((pickerView, adapter, position) -> {
                    adapter.selectCity = adapter.getItemData(position);
                })
                .setSubmitButtonOnClickListener(v -> {
                    City city = cityAdapter.selectCity;
                    UserEntity.self.setCityInfo(city.index, city.name, cityAdapter.province);
                    editService.submitCity();
                })
                .showBottomAt(owner.viewDataBinder().getRoot());
    }

    private class ProvincePickerAdapter extends PickerViewAdapter<List<String>> {
        public ProvincePickerAdapter(List<String> data) {
            super(data);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public String getItem(int position) {
            return data.get(position);
        }
    }

    private class CityPickerAdapter extends PickerViewAdapter<Map<String, City[]>> {

        private String province;
        private City[] cities;
        private City selectCity;

        public CityPickerAdapter(Map<String, City[]> data) {
            super(data);
        }

        @Override
        public int getCount() {
            return ArrayUtil.size(cities);
        }

        @Override
        public String getItem(int position) {
            return ArrayUtil.isEmpty(cities) ? "" : cities[position].name;
        }

        public void setProvince(String province) {
            if(MapUtil.notEmpty(data)) {
                this.province = province;
                this.cities = data.get(province);
                this.selectCity = cities[0];
                notifyDataSetChanged();
            }
        }

        public City getItemData(int position) {
            return ArrayUtil.isEmpty(cities) ? null : cities[position];
        }
    }

}
